version="";
appNumbers=4;
adfsVersion="2021";
image="10.164.2.213:4300/wfmobile/mobile";
maintainImage="10.164.2.213:4300/library/maintain";

if [ -n "$1" ];then
  version=${1,,};
else
  echo '  must input version!';

  exit 0;
fi

# maintain
if [ "$version" == "maintain" ];then
  maintainCounts=$(docker images | grep "$maintainImage" | awk '{print $3}' | wc -l);

  if [ $maintainCounts -eq 0 ];then
    echo "  pull the image: ${maintainImage}...";

    docker pull ${maintainImage} &> /dev/null;

    if [ $? -ne 0 ]; then
      echo '  image is not in docker registry!';

      exit 0;
    fi
  fi

  maintainApps=$(docker ps | grep maintain | wc -l);
  if [ $maintainApps -eq 1 ]; then
    echo '  completed!';
    
    exit 0;
  fi

  echo '  begin deploy...';

  docker rm -f wfmobile${appNumbers} &> /dev/null;
  docker run --restart=always --name=wfmobile$[ $appNumbers ] -p $[ 3300 + ($appNumbers - 1) ]:80 -m 512m --cpus=0.5 -d ${maintainImage} &> /dev/null;

  sleep 8;

  for (( index=1; index<$appNumbers; index++ ))
  do
    docker rm -f wfmobile${index} &> /dev/null;
  done

  echo '  deploy completed!'
  
  exit 0;
fi

# create image from local
if [ "${1,,}" == 'local' ]; then
  image='iworkflow';
else
  counts=$(docker images | grep "$image" | grep "$version" | awk '{print $3}' | wc -l);

  if [ $counts -eq 0 ];then
    echo "  pull the image: ${image}:${version}...";
    docker pull ${image}:$version &> /dev/null;

    if [ $? -ne 0 ]; then
      echo '  image is not exists, try again!';

      exit 0;
    fi

    echo '  pull completed!';
  fi
fi

echo '  begin deploy...';

for(( index = 1; index < $appNumbers; index++ ))
do
  echo "    update app [wfmobile${index}]...";
  docker rm -f wfmobile${index} &> /dev/null;
  docker run -e "ASPNETCORE_ENVIRONMENT=Production" --restart=always --name=wfmobile${index} -p $[ 3300 + ($index-1) ]:80 -m 512m -d ${image}:$version &> /dev/null;

  sleep 5;
  echo "    [wfmobile${index}] update completed!";
done

if [ 0 -lt `docker ps -a | grep "wfmobile${appNumbers}" | awk '{print $1}' | wc -l` ];then
  docker rm -f wfmobile${appNumbers} &> /dev/null;
fi

docker run -e "ASPNETCORE_ENVIRONMENT=Production" --restart=always --name=wfmobile${appNumbers} -p $[ 3300 + ($appNumbers-1) ]:80 -m 512m -d ${image}:$version &> /dev/null;

sleep 5;

echo '    change iptables configuration...';

sleep 5;

OLD_IFS=$IFS;
for rule in $(iptables -L DOCKER -n --line-number | grep -w dpt:80 | sort -n -r | awk '{print $1}')
do
  iptables -D DOCKER $rule &> /dev/null;
done

iptables -A DOCKER -p tcp -m tcp -s 10.164.2.133 --dport 80 -j ACCEPT &> /dev/null;

service iptables save &> /dev/null;
service iptables restart &> /dev/null;

echo '  iptables change completed';

sleep 2;

echo '  deploy completed!';
